<template>
  <div class="admin-notice-container">
    <!-- 导航栏 -->
    <header class="admin-header">

    </header>

    <!-- 主要内容 -->
    <main class="admin-main-content">
      <div class="container">
        <h2>公告管理</h2>
        <div class="admin-toolbar">
          <div class="toolbar-left">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索公告标题或内容"
                clearable
                style="width: 300px"
                @clear="fetchNoticeList"
                @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>
          <div class="toolbar-right">
            <el-button type="primary" @click="showAddDialog = true" class="add-button">
              <el-icon><Plus /></el-icon>
              添加公告
            </el-button>
          </div>
        </div>

        <!-- 公告列表 -->
        <div class="admin-notice-list">
          <el-table
              :data="noticeList"
              style="width: 100%"
              v-loading="loading"
              stripe
              border
              highlight-current-row
              @sort-change="handleSortChange"
          >
            <el-table-column prop="id" label="ID" width="80" sortable="custom" />
            <el-table-column prop="title" label="标题" min-width="200" sortable="custom" />
            <el-table-column prop="content" label="内容" min-width="300">
              <template #default="{row}">
                <div class="content-preview">{{ truncateContent(row.content) }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="viewCount" label="浏览次数" width="120" sortable="custom" />
            <el-table-column prop="publishTime" label="发布时间" width="180" sortable="custom">
              <template #default="{row}">
                {{ formatDateTime(row.publishTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right" align="center">
              <template #default="{row}">
                <el-tooltip content="查看详情" placement="top">
                  <el-button size="small" circle @click="viewNoticeDetail(row)">
                    <el-icon><View /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="编辑公告" placement="top">
                  <el-button size="small" type="warning" circle @click="editNotice(row)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </el-tooltip>
                <el-tooltip content="删除公告" placement="top">
                  <el-button size="small" type="danger" circle @click="confirmDeleteNotice(row.id)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="admin-pagination" v-if="total > 0">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :small="false"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="fetchNoticeList"
              @current-change="fetchNoticeList"
          />
        </div>
      </div>
    </main>

    <!-- 添加公告对话框 -->
    <el-dialog
        v-model="showAddDialog"
        title="添加公告"
        width="50%"
        :close-on-click-modal="false"
    >
      <el-form
          :model="addNoticeForm"
          :rules="noticeRules"
          ref="addFormRef"
          label-width="100px"
          label-position="top"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="addNoticeForm.title" placeholder="请输入公告标题" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
              v-model="addNoticeForm.content"
              type="textarea"
              :rows="10"
              placeholder="请输入公告内容"
              resize="none"
              maxlength="2000"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false" :disabled="addingNotice">取消</el-button>
          <el-button
              type="primary"
              @click="addNotice"
              :loading="addingNotice"
          >
            确认添加
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑公告对话框 -->
    <el-dialog
        v-model="showEditDialog"
        title="编辑公告"
        width="50%"
        :close-on-click-modal="false"
    >
      <el-form
          :model="editNoticeForm"
          :rules="noticeRules"
          ref="editFormRef"
          label-width="100px"
          label-position="top"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="editNoticeForm.title" placeholder="请输入公告标题" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
              v-model="editNoticeForm.content"
              type="textarea"
              :rows="10"
              placeholder="请输入公告内容"
              resize="none"
              maxlength="2000"
              show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false" :disabled="editingNotice">取消</el-button>
          <el-button
              type="primary"
              @click="updateNotice"
              :loading="editingNotice"
          >
            更新公告
          </el-button>
        </span>
      </template>
    </el-dialog>


    <!-- 公告详情对话框 -->
    <el-dialog
        v-model="showDetailDialog"
        :title="currentNotice.title"
        width="60%"
        top="5vh"
    >
      <div class="notice-detail">
        <div class="notice-meta">
          <span><el-icon><Calendar /></el-icon> 发布时间: {{ formatDateTime(currentNotice.publishTime) }}</span>
          <span><el-icon><View /></el-icon> 浏览次数: {{ currentNotice.viewCount }}</span>
        </div>
        <div class="notice-content" v-html="formatContent(currentNotice.content)"></div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="showDetailDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 页脚 -->
    <footer style="background-color: #f5f7fa; padding: 20px 0; border-top: 1px solid #e6e6e6;">
      <div class="container">
        <div class="footer-content" style="text-align: center;">
          <p style="color: #666; margin-bottom: 10px;">安心陪诊后台管理系统</p>
          <p style="color: #999; font-size: 12px;">
            &copy; 2025 安心陪诊平台 版权所有 |
            <a href="#" @click.prevent="goToUserAgreement" style="color: #999;">用户协议</a> |
            <a href="#" @click.prevent="goToPrivacyPolicy" style="color: #999;">隐私政策</a>
          </p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { Plus, Search, View, Edit, Delete, Calendar } from '@element-plus/icons-vue';

const router = useRouter();
const addFormRef = ref(null);
const editFormRef = ref(null);

// 表单验证方法
const validateForm = async () => {
  try {
    await addNoticeForm.value.validate();
    return true;
  } catch (error) {
    console.log('表单验证失败:', error);
    throw 'validation-failed';
  }
};

// 重置添加表单
const resetAddForm = () => {
  addNoticeForm.value = { title: "", content: "" };
  addFormRef.value?.resetFields();
};

// 重置编辑表单
const resetEditForm = () => {
  editNoticeForm.value = { id: "", title: "", content: "" };
  editFormRef.value?.resetFields();
};

// 公告列表相关
const noticeList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchKeyword = ref("");
const sortProp = ref("");
const sortOrder = ref("");

// 添加公告相关
const showAddDialog = ref(false);
const addingNotice = ref(false);
const addNoticeForm = ref({
  title: "",
  content: ""
});

// 编辑公告相关
const showEditDialog = ref(false);
const editingNotice = ref(false);
const editNoticeForm = ref({
  id: "",
  title: "",
  content: ""
});

const noticeRules = ref({
  title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
    { max: 200, message: '标题长度不能超过200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
    { max: 2000, message: '内容长度不能超过2000个字符', trigger: 'blur' }
  ]
});

// 公告详情相关
const showDetailDialog = ref(false);
const currentNotice = ref({
  id: "",
  title: "",
  content: "",
  viewCount: 0,
  publishTime: ""
});

// 获取公告列表
const fetchNoticeList = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value,
      sortProp: sortProp.value,
      sortOrder: sortOrder.value
    };

    const response = await axios.get(BASE_URL + '/v1/notice/notices', {
      params,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
      }
    });

    if (response.data.state === 2000) {
      // 确保 noticeList 是数组
      noticeList.value = Array.isArray(response.data.data) ? response.data.data : [];
      total.value = response.data.total || noticeList.value.length;
    } else {
      noticeList.value = []; // 失败时清空表格
      ElMessage.error(response.data.message || "获取公告列表失败");
    }
  } catch (error) {
    noticeList.value = []; // 异常时清空表格
    console.error("获取公告列表出错:", error);
    ElMessage.error(error.response?.data?.message || "获取公告列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索特定公告
const selectNotice = async () => {
  try {
    loading.value = true;
    const response = await axios.post(
        BASE_URL + '/v1/notice/select',
        { title: searchKeyword.value, content: searchKeyword.value },
        { headers: { 'Authorization': `Bearer ${localStorage.getItem('managerToken')}` } }
    );

    if (response.data.state === 2000) {
      // 处理单条数据情况 - 如果是对象就转为数组
      let data = response.data.data;
      if (data && !Array.isArray(data)) {
        data = [data]; // 将单个对象转为数组
      }

      console.log("搜索公告结果:", data);
      noticeList.value = data || []; // 确保是数组
      total.value = noticeList.value.length;
      ElMessage.success("搜索成功");
    } else {
      noticeList.value = [];
      ElMessage.error(response.data.message || "搜索公告失败");
    }
  } catch (error) {
    noticeList.value = [];
    console.error("搜索公告出错:", error);
    ElMessage.error(error.response?.data?.message || "搜索公告失败");
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  if (searchKeyword.value.trim() === '') {
    fetchNoticeList();
  } else {
    selectNotice();
  }
};

// 添加公告
const addNotice = async () => {
  try {
    await addFormRef.value.validate();
    addingNotice.value = true;

    const response = await axios.post(
        `${BASE_URL}/v1/notice/insert`,
        addNoticeForm.value,
        {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
          }
        }
    );

    if (response.data.state === 2000) {
      ElMessage.success("添加公告成功");
      showAddDialog.value = false;
      resetAddForm();
      fetchNoticeList();
    } else {
      ElMessage.error(response.data.message || "添加公告失败");
    }
  } catch (error) {
    if (error.validation) return; // 验证失败不显示错误消息
    console.error("添加公告出错:", error);
    ElMessage.error(error.response?.data?.message || "添加公告失败");
  } finally {
    addingNotice.value = false;
  }
};


// 编辑公告 - 打开对话框
const editNotice = (notice) => {
  editNoticeForm.value = {
    id: notice.id,
    title: notice.title,
    content: notice.content
  };
  showEditDialog.value = true;
};


// 更新公告
const updateNotice = async () => {
  try {
    await editFormRef.value.validate();
    editingNotice.value = true;

    const response = await axios.post(
        `${BASE_URL}/v1/notice/update`,
        editNoticeForm.value,
        {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
          }
        }
    );

    if (response.data.state === 2000) {
      ElMessage.success("更新公告成功");
      showEditDialog.value = false;
      resetEditForm();
      fetchNoticeList();
    } else {
      ElMessage.error(response.data.message || "更新公告失败");
    }
  } catch (error) {
    if (error.validation) return; // 验证失败不显示错误消息
    console.error("更新公告出错:", error);
    ElMessage.error(error.response?.data?.message || "更新公告失败");
  } finally {
    editingNotice.value = false;
  }
};


// 删除公告
const deleteNotice = async (id) => {
  try {
    const response = await axios.post(
        BASE_URL + '/v1/notice/delete',
        null,
        {
          params: { id },
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('managerToken')}`
          }
        }
    );

    if (response.data.state === 2000) {
      ElMessage.success("删除公告成功");
      // 如果当前页只有一条数据且不是第一页，则返回上一页
      if (noticeList.value.length === 1 && currentPage.value > 1) {
        currentPage.value--;
      }
      fetchNoticeList();
    } else {
      ElMessage.error(response.data.message || "删除公告失败");
    }
  } catch (error) {
    console.error("删除公告出错:", error);
    ElMessage.error(error.response?.data?.message || "删除公告失败");
  }
};


// 确认删除公告
const confirmDeleteNotice = (id) => {
  ElMessageBox.confirm(
      '确定要删除这条公告吗？删除后无法恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            deleteNotice(id).finally(() => {
              instance.confirmButtonLoading = false;
              done();
            });
          } else {
            done();
          }
        }
      }
  ).catch(() => {});
};

// 查看公告详情
const viewNoticeDetail = (notice) => {
  currentNotice.value = { ...notice };
  showDetailDialog.value = true;
};


// 处理排序
const handleSortChange = ({ prop, order }) => {
  sortProp.value = prop;
  sortOrder.value = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : '';
  fetchNoticeList();
};

// 格式化内容 - 将换行转换为<br>标签
const formatContent = (content) => {
  if (!content) return '';
  return content.replace(/\n/g, '<br>');
};

// 截断内容用于预览
const truncateContent = (content) => {
  if (!content) return '';
  return content.length > 100 ? content.substring(0, 100) + '...' : content;
};

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return "未知时间";
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-');
};

const goToUserAgreement = () => {
  router.push("/userAgreement");
};

const goToPrivacyPolicy = () => {
  router.push("/privacyPolicy");
};

onMounted(() => {
  fetchNoticeList();
});
</script>

<style scoped>
.admin-notice-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.admin-header {
  color: white;
  padding: 15px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 25px;
}

h2 {
  font-size: 24px;
  color: #1a365d;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e2e8f0;
  font-weight: 600;
}

.admin-main-content {
  flex: 1;
  padding: 20px 0;
}

.admin-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.admin-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  .add-button {
    padding: 10px 15px;
    font-weight: 500;
  }
}

.admin-notice-list {
  background-color: white;
  border-radius: 6px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

  .el-table {
    border-radius: 6px;
    overflow: hidden;

    :deep(th) {
      background-color: #f8fafc !important;

      font-weight: 600;
    }

    :deep(.el-table__row--striped) {
      background-color: #fafafa;
    }

    :deep(.el-table__row:hover) {
      background-color: #f5f7fa;
    }
  }

  .content-preview {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: 1.5;
    max-height: 3em;
    white-space: normal;
  }
}

.admin-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 15px;
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.notice-detail {
  padding: 0 10px;
  line-height: 1.6;

  .notice-meta {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    color: #666;
    font-size: 14px;
    padding-bottom: 10px;
    border-bottom: 1px dashed #eaeaea;

    span {
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }

  .notice-content {
    padding: 15px;
    background: #f9f9f9;
    border-radius: 4px;
    line-height: 1.8;
    white-space: pre-wrap;
    font-size: 15px;
    color: #333;
  }
}


/* 响应式设计 */
@media (max-width: 768px) {
  .admin-header .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .admin-toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;

    .toolbar-left, .toolbar-right {
      width: 100%;
    }

    .el-input {
      width: 100% !important;
    }
  }

  .el-dialog {
    width: 90% !important;
  }

  .notice-meta {
    flex-direction: column;
    gap: 8px;
  }
}
</style>